import app from '@/app'
import Factory from './factory'
import { totalGoods } from '@/api/store/order'

class GoodsFactory extends Factory {

  async getData(start, end, data) {
    const item = {}
    const time = [start.unix(), end.unix()]

    // 请求
    await this.getDataList('money', time, item)
    await this.getDataList('goods_count', time, item)
    await this.getDataList('profit_money', time, item)

    if(Object.keys(item).length > 0) {
      data.item = item
    }
  }

  // 请求列表
  async getDataList(type, time, item) {
    (await totalGoods({ time, type })).forEach(goods => {
      item[goods.goods_id] = {
        c: goods.count,
        gc: goods.goods_count,
        m: goods.money,
        pm: goods.profit_money
      }
    })
  }

  // 处理统计
  total() {
    // 循环天
    this.day.forEach(data => {
      // 循环列表
      Object.keys(data.item ?? {}).forEach(id => {
        const goods = data.item[id]

        // 统计年
        this.year[id] = this.totalHandle(this.year[id], goods)
        
        // 统计季度 
        this.quarter[data.id[0]][id] = this.totalHandle(this.quarter[data.id[0]][id], goods)
        
        // 统计月
        this.month[data.id[1]][id] = this.totalHandle(this.month[data.id[1]][id], goods)
      })
    })
  }

  totalHandle(origin, data) {
    return {
      c: app.math.add(origin?.c ?? 0, data.c),
      gc: app.math.add(origin?.gc ?? 0, data.gc),
      m: app.math.add(origin?.m ?? 0, data.m),
      pm: app.math.add(origin?.pm ?? 0, data.pm),
    }
  }

  // 查询统计数据
  getTotal(type, index, day) {
    const data = {
      year: () => this.year,
      quarter: () => this.quarter[index],
      month: () => this.month[index],
      day: () => this.getDay(day.month(), day.day()).item ?? []
    }[type]()

    return Object.keys(data).map(id => {
      return {
        id,
        ...data[id]
      }
    })
  }
}

export default GoodsFactory